<?php
/**
 * Created by PhpStorm.
 * User: lzy 林子彦
 * Date: 2018/6/1
 * Time: 上午1:15
 */
namespace App\Admin\Models;
use App\Base\Models\BaseModel;
class  MenuModel extends  BaseModel {
    public $table="menu";
    public $timestamps=false;
    protected $appends = ['pname'];
    public function getPnameAttribute(){
        $pid=$this->pid;
        $pname=$this->newQuery()->where("id",$pid)->pluck("title");
        $prturn=!empty($pname->toArray())?$pname:'顶级节点';
        return $prturn;
    }
    public function getReturnNode($tree=TRUE){
        static $tree_nodes = array();
        if ( $tree && !empty($tree_nodes[(int)$tree]) ) {
            return $tree_nodes[$tree];
        }
        if((int)$tree){
            $list = $this->newQuery()->select("id","pid","title","url","tip","hide")->orderBy("sort","asc")->get()->toArray();
            foreach ($list as $key => $value) {
                if( stripos($value['url'],MODULE_NAME)!==0 ){
                    $list[$key]['url'] = strtolower(MODULE_NAME.'/'.$value['url']);
                }
            }
            $nodes = list_to_tree($list,$pk='id',$pid='pid',$child='operator',$root=0);
            foreach ($nodes as $key => $value) {
                if(!empty($value['operator'])){
                    $nodes[$key]['child'] = $value['operator'];
                    unset($nodes[$key]['operator']);
                }
            }
        } else {
            $nodes = $this->newQuery()->select("title","url","tip","pid")->orderBy("sort","asc")->get()->toArray();
            foreach ($nodes as $key => $value) {
                if (stripos($value['url'], MODULE_NAME) !== 0) {
                    $nodes[$key]['url'] = strtolower(MODULE_NAME . '/' . $value['url']);
                }
            }
        }
        return $nodes;

    }
}